<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>写游记</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="http://47.106.66.89:8080/js/vue.min.js"></script>
    <script src="http://47.106.66.89:8080/js/axios.min.js"></script>
    <link href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css" rel="stylesheet">
    <script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
    <script src="js/public.js"></script>
    <link href="css/public.css" rel="stylesheet">
    <link href="css/travrlogue.css" rel="stylesheet">
</head>
<body>

<div id="app">
    <public @user-loaded="handleUserLoaded" ref="loginComponent">
        <template v-slot:header-ul>
            <ul class="header-ul">
                <li style="width: 60px;">首页</li>
                <li style="width: 74px;">目的地</li>
                <li style="width: 88px;">旅游攻略</li>
                <li style="width: 70px;">去旅行</li>
                <li style="width: 54px">社区</li>
                <li style="width: 74px">找搭子</li>
            </ul>
        </template>
        <template v-slot:nologin>
            <div class="header-login">
                <a href="javascript:void(0)"><img src="images/qq.png" title="QQ登录"/></a>
                <a href="javascript:void(0)"><img src="images/wx.png" title="微信登录"/></a>
                <a class="lar" href="lar.html" style="font-weight: bold;">登录</a>
                <span>|</span>
                <a class="lar" href="lar.html" style="font-weight: bold;">注册</a>
            </div>
        </template>
        <template v-slot:logined="user">
            <div class="header-login">
                <a>打卡</a>
                <a class="msg">消息<i class="bi bi-caret-down-fill"></i></a>
                <a class="per"><img :src="user.avatar"><i class="bi bi-caret-down-fill"></i></a>
            </div>
            <!--消息下拉菜单-->
            <div class="tips msg-tips">
                <ul>
                    <li>私信</li>
                    <li>系统通知</li>
                    <li>回复消息</li>
                </ul>
            </div>
            <!--用户下拉菜单-->
            <div class="tips user-tips">
                <ul>
                    <li><i class="bi bi-pencil-square"></i>写游记</li>
                    <li><i class="bi bi-question-diamond"></i>我的问答</li>
                    <li><i class="bi bi-star-fill"></i>我的收藏</li>
                    <li><i class="bi bi-gear"></i>设置</li>
                    <li @click="loginout"><i class="bi bi-box-arrow-left"></i>退出</li>
                </ul>
            </div>
        </template>
        <template v-slot:container>
            <div class="container-img">
                <div class="container-img-img"><img :src="backImg" ></div>
                <input type="file" style="display: none" ref="backImg"
                       @change="handleBackImg" accept=".jpg,.jpeg,.png">
                <div v-if="backImg == '' " class="container-img-add">
                    <i @click="addBackImg" class="bi bi-image"></i>
                    <span>
                        <h3>设置游记头图</h3>
                        <p>图片建议选择尺寸大于1680px的高清大图，如相机原图</p>
                    </span>
                </div>
                <div v-else class="re-img">
                    <div>
                        <span @click="addBackImg"><i class="bi bi-image"></i>设置头图</span>
                    </div>
                </div>
                <div class="container-title"><input type="text" placeholder="填写游记标题" v-model="title"></div>
            </div>
            <div class="container-main">
                <div class="main-left">
                    <div v-for="(item,index) in sortedContent" :key="index">
                        <div v-if="item.type === 'paragraph' ">
                            <div class="main-left-paragraph">
                                <h2><span>{{item.value}}</span></h2>
                                <span class="pa-span">
                                <a @click="editPara(item.index)"><i class="bi bi-pencil-square"></i></a>
                                <a @click="delPara(item.index)"><i class="bi bi-trash3"></i></a>
                            </span>
                            </div>
                            <div class="main-left-textarea">
                                <textarea :id="'textarea-' + item.index"
                                          cols="30" rows="1" style="overflow: hidden;height: 30px;"
                                          @focus="updateTextareaId('textarea-' + item.index)"
                                          @input="writeInto(item.index, $event.target.value)"
                                          :value="getTextByIndex(item.index)"
                                          v-autoresize></textarea>
                            </div>
                        </div>
                        <div v-if="item.type === 'image' ">
                            <div class="main-left-img">
                                <img :src="item.value" :style="{ transform: `rotate(${item.rotation}deg)` }" alt="image">
                                <span class="img-span">
                                    <a @click="leftRota(item.index)"><i class="bi bi-arrow-counterclockwise"></i></a>
                                    <a @click="rightRota(item.index)"><i class="bi bi-arrow-clockwise"></i></a>
                                    <a @click="delImg(item.index)"><i class="bi bi-x"></i></a>
                                </span>
                            </div>
                            <div class="main-left-textarea">
                                <textarea :id="'textarea-' + item.index"
                                          cols="30" rows="1"
                                          style="overflow: hidden;height: 30px;"
                                          @focus="updateTextareaId('textarea-' + item.index)"
                                          @input="writeInto(item.index, $event.target.value)"
                                          :value="getTextByIndex(item.index)"
                                          v-autoresize>
                                </textarea>
                            </div>
                        </div>
                    </div>
                    <div class="textarea-wrapper">
                        <textarea id="auto-grow-textarea"
                                  placeholder="从这里开始写游记正文..."
                                  name="auto-grow-textarea"
                                  @focus="updateTextareaId('auto-grow-textarea')"
                                  @input="writeInto(item.index, $event.target.value)"></textarea>
                    </div>
                </div>
                <div class="main-right">
                    <div class="sticky-sidebar" id="sticky-sidebar">
                        <div class="right-first">
                            <ul>
                                <li @click="insertImg"><i class="bi bi-image"></i>插入图片</li>
                                <input @change="handleFileChange" type="file"
                                       ref="inputFile" style="display: none" accept=".jpg,.jpeg,.png"/>
                                <li class="emotion"><i class="bi bi-emoji-smile"></i>插入表情</li>
                                <li @click="insertPara"><i class="bi bi-text-paragraph"></i>插入段落标题</li>
                            </ul>
                            <div class="right-first-para" id="right-first-para" v-if="paraVisible">
                                <div>
                                    <input class="right-first-para-input" v-model="inputValue"
                                           type="text" placeholder="请输入段落名称">
                                </div>
                                <a @click="confirmAction">确定</a>
                            </div>
                        </div>
                        <div class="right-second"><a @click="saveDraft"><i class="bi bi-file-earmark-text"></i>保存草稿</a></div>
                        <div class="right-third">
                            <div>游记目录</div>
                            <div class="right-third-paragraph">
                                <ul>
                                    <li v-for="(item,index) in content.paragraphs" :key="index">
                                        <span>{{formatIndex(index+1)}}&nbsp;/</span><a>&nbsp;{{item.value}}</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="main-preview">
                    <a @click="preView">预览</a>
                    <a @click="publicTravelogue">发表游记</a>
                </div>
            </div>
        </template>
    </public>
</div>

<script src="js/jquery.min.js"></script>
<script src="js/jquery.qqFace.js"></script>
<script>
    const token = localStorage.getItem('token');
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
    var v = new Vue({
        el: "#app",
        data: {
            content: {
                images: [],
                paragraphs: [],
                texts:[]
            },
            user: {},
            sortedContents: [],
            paraVisible: false,
            isEditing: false,
            editingIndex: null,
            inputValue:'',
            contentIndex: 0,
            backImg: '',
            title: '',
            textareaId: 'auto-grow-textarea',
            travelogueId: 0
        },
        directives: {
            autoresize: {
                inserted(el) {
                    el.style.height = 'auto';  // 重置高度
                    el.style.height = el.scrollHeight + 'px';  // 设置初始高度
                    el.addEventListener('input', () => {
                        el.style.height = 'auto';  // 重置高度
                        el.style.height = el.scrollHeight + 'px';  // 设置新高度
                    });
                }
            }
        },
        computed: {
            sortedContent() {
                // 合并三个部分并按index排序
                this.sortedContents = [...this.content.images, ...this.content.paragraphs,...this.content.texts]
                    .sort((a, b) => a.index - b.index);
                return this.sortedContents;
            }

        },
        mounted(){
            // 初始化表情插件
            $('.emotion').qqFace({
                id: 'facebox',
                assign: 'auto-grow-textarea',
                path: 'arclist/' // 表情存放的路径
            });

            window.addEventListener('scroll', this.updateSidebarPosition);
            window.addEventListener('resize', this.updateSidebarPosition);
            // Initial call to set the position correctly
            this.updateSidebarPosition();

            this.loadData();
        },
        beforeDestroy() {
            window.removeEventListener('scroll', this.updateSidebarPosition);
            window.removeEventListener('resize', this.updateSidebarPosition);
        },
        methods: {
            loginout(){
                axios.get("/users/loginout").then(res =>{
                    this.$refs.loginComponent.user = null;
                    this.user = {};
                    location.href = 'index.html'
                })
            },
            //加载保存的数据
            loadData() {
                const one =  JSON.parse(sessionStorage.getItem('sortedContents'));
                const two = sessionStorage.getItem('travelogueId');
                const three = sessionStorage.getItem('title');
                const four = sessionStorage.getItem('backImg');
                const five = sessionStorage.getItem('contentIndex');

                if (one && two && three && four && five){
                    this.sortedContents = one;
                    this.travelogueId = two;
                    this.title = three;
                    this.backImg = four;
                    this.contentIndex = five;

                    sessionStorage.clear();
                }
            },
            //预览
            async preView(){
                if (this.user === null){
                    this.$alert("用户未登录！请先登录")
                    return
                }
                axios.post("/travelogues/addNew",{
                    title: this.title,
                    backImg:this.backImg,
                    userId: this.user.id,
                    travelogueId: this.travelogueId,
                    isDraft: 1
                }).then( res =>{
                    if (res.data.code === 200){
                        this.travelogueId = res.data.data;
                        axios.get("/contents/setUnUse?travelogueId=" + this.travelogueId).then(res => {
                            const promises = this.sortedContents.map(item => {
                                return axios.post("/contents/content", {
                                    travelogueId: this.travelogueId,
                                    contentId: item.id,
                                    contentType: item.type,
                                    contentValue: item.value,
                                    contentIndex: item.index
                                }).then(function (res) {
                                    if (res.data.code === 200) {
                                        item.id = res.data.data;
                                    }
                                });
                            });
                            // 等待所有的请求完成
                            Promise.all(promises).then(() => {
                                sessionStorage.setItem('sortedContents', JSON.stringify(this.sortedContents));
                                sessionStorage.setItem('travelogueId', this.travelogueId);
                                sessionStorage.setItem('title', this.title);
                                sessionStorage.setItem('backImg', this.backImg);
                                sessionStorage.setItem('contentIndex', this.contentIndex);
                                location.href = 'preView.html?travelogueId=' + this.travelogueId;
                            }).catch(error => {
                                console.error("Error during saving contents:", error);
                            });
                        }).catch(error => {
                            console.error("Error during setUnUse:", error);
                        });

                    }else{
                        this.$alert(res.data.message);
                    }
                });
            },
            async saveDraft(){
                if (this.user === null){
                    this.$alert("用户未登录！请先登录")
                    return
                }
                axios.post("/travelogues/addNew",{
                    title: this.title,
                    backImg:this.backImg,
                    userId: this.user.id,
                    travelogueId: this.travelogueId,
                    isDraft: 1
                }).then( res =>{
                    if (res.data.code === 200){
                        this.travelogueId = res.data.data;
                        axios.get("/contents/setUnUse?travelogueId=" + this.travelogueId).then(res =>{

                        })

                        this.sortedContents.forEach( item => {
                            axios.post("/contents/content",{
                                travelogueId:this.travelogueId,
                                contentId: item.id,
                                contentType:item.type,
                                contentValue:item.value,
                                contentIndex:item.index
                            }).then(function (res) {
                                if (res.data.code === 200){
                                    item.id = res.data.data
                                }else{

                                }
                            })
                        })
                        this.$message("保存草稿成功！")
                    }else{
                        this.$alert(res.data.message);
                    }
                });
            },
            handleUserLoaded(user) {
                if (user == null){
                    location.href = 'lar.html';
                    return
                }
                this.user = user;
            },
            // 根据索引获取文本内容
            getTextByIndex(index) {
                const textObj = this.content.texts.find(item => item.index === index);
                return textObj ? textObj.value : '';
            },
            writeInto(index, value) {
                const textIndex = this.content.texts.findIndex(item => item.index === index);
                if (textIndex !== -1) {  // 检查索引是否有效
                    this.content.texts[textIndex].value = value;
                } else {
                    this.content.texts.push({
                        id: null,
                        type: 'text',
                        value: value,
                        index: index
                    });
                }
            },
            async publicTravelogue(){
                if (this.user === null){
                    this.$alert("用户未登录！请先登录")
                    return
                }
                if (this.title === ''){
                    this.$alert("标题不能为空")
                    return
                }
                axios.post("/travelogues/addNew",{
                        title: this.title,
                        backImg:this.backImg,
                        userId: this.user.id,
                        travelogueId:this.travelogueId,
                        isDraft: 0
                }).then( res =>{
                    if (res.data.code === 200){
                        this.travelogueId = res.data.data;

                        this.sortedContents.forEach( item => {
                                axios.post("/contents/content",{
                                    travelogueId:this.travelogueId,
                                    contentType:item.type,
                                    contentValue:item.value,
                                    contentIndex:item.index,
                                    contentId: item.id
                                }).then( function (res) {
                                    if (res.data.code === 200){
                                        item.id = res.data.data;
                                    }else{

                                    }
                                })
                        })
                        this.$message("发表游记成功！快看看吧")

                    }else{
                        this.$alert(res.data.message);
                    }
                });
            },
            updateSidebarPosition() {
                var sidebar = document.getElementById('sticky-sidebar');
                var container = document.querySelector('.container-main');
                var rightFirstPara = document.getElementById('right-first-para');
                var containerRect = container.getBoundingClientRect();
                var sidebarRect = sidebar.getBoundingClientRect();
                var containerTop = containerRect.top + window.scrollY;
                var containerBottom = containerTop + containerRect.height;
                var viewportHeight = window.innerHeight;
                var scrollY = window.scrollY;

                if (scrollY > containerTop && scrollY < containerBottom - sidebarRect.height) {
                    sidebar.style.position = 'fixed';
                    sidebar.style.top = '0';
                    if (rightFirstPara) {
                        rightFirstPara.style.position = 'fixed';
                        rightFirstPara.style.top = '75px'; // Ensure it follows the scrolling
                        rightFirstPara.style.left = '360px'; // Keep the left offset
                    }
                } else if (scrollY >= containerBottom - sidebarRect.height) {
                    sidebar.style.position = 'absolute';
                    sidebar.style.top = (containerRect.height - sidebarRect.height) + 'px';
                    if (rightFirstPara) {
                        rightFirstPara.style.position = 'absolute';
                        rightFirstPara.style.top = (containerRect.height - sidebarRect.height + (window.innerHeight * 0.6)) + 'px'; // Adjust as needed
                        rightFirstPara.style.left = '-260%'; // Keep the left offset
                    }
                } else {
                    sidebar.style.position = 'absolute';
                    sidebar.style.top = '0';
                    if (rightFirstPara) {
                        rightFirstPara.style.position = 'absolute';
                        rightFirstPara.style.top = '60%'; // Adjust as needed
                        rightFirstPara.style.left = '-260%'; // Keep the left offset
                    }
                }
            },
            initQQFace() {
                $('.emotion').qqFace({
                    id: 'facebox',
                    assign: this.textareaId,
                    path: 'arclist/' // 表情存放的路径
                });
            },
            insertImg() {
                this.$refs.inputFile.click();
            },
            async handleFileChange(event) {
                const file = event.target.files[0];
                if (file) {
                    const allowedTypes = ['image/jpeg', 'image/png'];
                    if (!allowedTypes.includes(file.type)) {
                        this.$alert('只能上传 jpg 或 png 格式的图片');
                        return
                    }

                    let formData = new FormData();
                    formData.append('file', file);

                    await axios.post('/travelogues/upload',
                        formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res =>{
                        if (res.data.code === 200){
                            this.content.images.push({
                                id: null,
                                type: 'image',
                                value: res.data.data,
                                index: this.contentIndex++,
                                rotation: 0
                            });
                        }else{
                            this.$alert(res.data.message)
                        }
                    })

                }
            },
            insertPara(){
                this.paraVisible = !this.paraVisible;
                if( this.paraVisible === true){
                    this.isEditing = false;
                }
            },
            editPara(index) {
                // console.log(index + '......')
                const para = this.content.paragraphs.find(item => item.index === index);
                if (para) {
                    this.inputValue = para.value;
                    this.isEditing = true;
                    this.editingIndex = this.content.paragraphs.indexOf(para);
                    this.paraVisible = true;
                }
            },
            confirmAction() {
                if (this.inputValue === '') {
                    this.$alert('请输入段落名称');
                    return;
                }
                if (this.isEditing) {
                    this.content.paragraphs[this.editingIndex].value = this.inputValue;
                } else {
                    this.content.paragraphs.push({
                        id: null,
                        type: 'paragraph',
                        value: this.inputValue,
                        index: this.contentIndex++
                    });
                }
                this.inputValue = '';
                this.paraVisible = false;
                this.isEditing = false;
                this.editingIndex = null;
            },
            delPara(index) {
                const paraIndex = this.content.paragraphs.findIndex(item => item.index === index);
                if (paraIndex !== -1) {
                    this.content.paragraphs.splice(paraIndex, 1);
                }

                const textIndex = this.content.texts.findIndex(item => item.index === index);
                if (textIndex !== -1) {
                    this.content.texts.splice(textIndex, 1);
                }
            },
            delImg(index){
                // console.log(index);
                const imgIndex = this.content.images.findIndex(item => item.index === index);
                if (imgIndex !== -1) {
                    this.content.images.splice(imgIndex, 1);
                }
            },
            leftRota(index){
                // console.log(index)
                const imgIndex = this.content.images.findIndex(item => item.index === index);
                this.content.images[imgIndex].rotation -= 90;
            },
            rightRota(index){
                const imgIndex = this.content.images.findIndex(item => item.index === index);
                this.content.images[imgIndex].rotation += 90;
            },
            formatIndex(index) {
                return String(index).padStart(2, '0');
            },
            addBackImg(){
                this.$refs.backImg.click();
            },
            async handleBackImg(event){
                const file = event.target.files[0];
                if (file) {
                    const allowedTypes = ['image/jpeg', 'image/png'];
                    if (!allowedTypes.includes(file.type)) {
                        this.$alert('只能上传 jpg 或 png 格式的图片');
                        return
                    }

                    let formData = new FormData();
                    formData.append('file', file);

                    await axios.post('/travelogues/upload',
                        formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res =>{
                            if (res.data.code === 200){
                                this.backImg = res.data.data;
                            }else{
                                this.$alert(res.data.message)
                            }
                        })
                }
            },
            updateTextareaId(id) {
                this.textareaId = id;
                this.initQQFace();  // 重新初始化 qqFace 插件
            }
        }
    })

    // 获取 URL 的查询部分
    const queryString = window.location.search;
    // 解析查询部分
    const params = new URLSearchParams(queryString);
    // 获取 travelogueId 参数的值
    const tid = params.get("travelogueId");
    // 检查 travelogueId 是否存在，并进行后续操作
    if (tid != null && tid !== '') {
        v.travelogueId = tid;
        axios.get("/travelogues/getOne?travelogueId="+tid).then(res =>{
            if (res.data.code == 200){
                let result = res.data.data;
                v.title = result.title;
                v.backImg = result.backImg;
                axios.get("/contents/getAll?travelogueId="+tid).then(res =>{
                    if (res.data.code == 200){
                        let list = res.data.data;
                        list.forEach( item => {
                            if (v.contentIndex <= item.contentIndex){
                                v.contentIndex = item.contentIndex + 1;
                            }

                            if (item.contentType == 'image'){
                                v.content.images.push({
                                    id: item.contentId,
                                    type: item.contentType,
                                    value: item.contentValue,
                                    index: item.contentIndex,
                                })

                            }else if(item.contentType == 'text'){
                                v.content.texts.push({
                                    id: item.contentId,
                                    type: item.contentType,
                                    value: item.contentValue,
                                    index: item.contentIndex
                                });
                            }else{
                                v.content.paragraphs.push({
                                    id: item.contentId,
                                    type: item.contentType,
                                    value: item.contentValue,
                                    index: item.contentIndex
                                })
                            }
                        })
                    };
                })
            }
        })
    }


    document.addEventListener('DOMContentLoaded', function () {
        // Auto grow the textarea
        // JavaScript 部分
        let textareas = document.querySelectorAll('.main-left-textarea textarea, .textarea-wrapper textarea');

        function autoGrow(textarea) {
            textarea.style.height = 'auto';  // 重置高度
            var contentHeight = textarea.scrollHeight;
            textarea.style.height = contentHeight + 'px';
            textarea.parentElement.style.height = contentHeight + 'px';
        }

        textareas.forEach(textarea => {
            textarea.addEventListener('input', () => autoGrow(textarea));
            autoGrow(textarea);  // 初始化时调用
        });
    });


    function replace_em(str) {
        let processedMsg = str;
        processedMsg = processedMsg.replace(/\</>g, '&lt;');
        processedMsg = processedMsg.replace(/\>/g, '&gt;');
        processedMsg = processedMsg.replace(/\n/g, '<br/>');
        processedMsg = processedMsg.replace(/\[em_([0-9]*)\]/g, '<img src="w2e/arclist/$1.gif" border="0" />');
        return processedMsg;
    }

    $(function () {
        $(document).on('click', '.emotion', function () {
            v.initQQFace();
            $('#facebox').css({
                'display': 'block',
                'position': 'absolute',
                'top': '70px',
                'left': '0',
                'z-index': '10000'
            });
        });
    });


</script>

</body>
</html>